package com.xxl.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;

import java.util.Locale;


/**
 * 自动以地区切换器，目的是解决页面国际化的请求
 * @author xxl
 * @date 2023/3/5
 */

public class ChangeLocale implements LocaleResolver {

    public ChangeLocale() {
        System.out.println("ChangeLocale类被spring管理");
    }

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        //默认地区
        Locale defaultLocale = Locale.getDefault();
        //解析前端的参数
        String language = request.getParameter("language");
        if (!StringUtils.isEmpty(language)) {
            String[] s = language.split("_");
            //如果是zh_CN，那配置了国际化的相关的配置则会选择中国语言
            defaultLocale = new Locale(s[0],s[1]);
            System.out.println("前端的参数=" + language+"，地区="+defaultLocale);
        }
        return defaultLocale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}
